#!/bin/sh

# fail if any commands fails
set -e
# debug log
#set -x

show_usage (){
    printf "Usage: $0 [options [parameters]]\n"
    printf "\n"
    printf "Mandatory options:\n"
    printf " -p|--pwad          [game pwad file]\n"
    printf "\n"
    printf "Options:\n"
    printf " -d|--game-dir      [/path/to/doom/base/directory] (Optional, default: '~/games/doom')\n"
    printf " -h|--help, Print help\n"

exit
}

if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
  show_usage
fi
if [ -z "$1" ]; then
  show_usage
fi

while [ -n "$1" ]; do
  case "$1" in
      --game-dir|-d)
        shift
        param_game_dir=$1
        ;;
     --pwad|-p)
        shift
        #echo "INFO: param - pwad: $1"
        param_pwad=$1
        ;;
     *)
        show_usage
        ;;
  esac
shift
done


### Configuration
if [ -z "$param_game_dir" ]; then
      param_game_dir="$HOME/games/doom"
fi
if [ -z "$param_pwad" ]; then
  echo "ERROR: pwad parameter is mandatory"
  exit 1
fi

config_iwads_dir="$param_game_dir/wads/iwads"
config_pwad_basegame=$(awk -F/ '{print $7}' <<< ${param_pwad})
#echo "INFO: iwad name: $config_pwad_basegame"
config_pwad_name=$(awk -F/ '{print $10}' <<< ${param_pwad})
config_pwad_name=$(basename -- "${config_pwad_name%.*}")
#echo "INFO: pwad name: $config_pwad_name"

# Get maps from pwad
gzdoom -iwad "$config_iwads_dir/$config_pwad_basegame.wad" -file "$param_pwad" -norun -hashfiles > /dev/null || true

if [ "$config_pwad_basegame" = "doom2" ]; then
    config_pwad_map=$(cat fileinfo.txt | grep "$config_pwad_name" | grep -e " MAP" -e " maps/" | awk '{print $4}' | sed -e "s/^MAP//" -e 's/,//g' | shuf -n 1)
    if [ -z "$config_pwad_map" ]; then
        config_pwad_map=$(cat fileinfo.txt | grep "$config_pwad_name" | grep " maps/" | awk '{print $4}' | sed -e "s/^maps\/map//" -e 's/.wad,//g' | shuf -n 1)
    fi
    #echo "INFO: pwad map number: $config_pwad_map"

    mapnumbercheck=$(echo "$config_pwad_map" | awk '$0 ~/[^0-9]/ { print "NOT_NUMBER" }')
elif [ "$config_pwad_basegame" = "doom" ]; then
    config_pwad_map=$(cat fileinfo.txt | grep "$config_pwad_name" | grep -E " E[1-5]M" | awk '{print $4}' | shuf -n 1 | sed -r 's/[EM]+/ /g' | sed -e "s/^0//" -e 's/,//g')
    #echo "INFO: pwad map number: $config_pwad_map"
elif [ "$config_pwad_basegame" = "heretic" ]; then
    config_pwad_map=$(cat fileinfo.txt | grep "$config_pwad_name" | grep -E " E[1-5]M" | awk '{print $4}' | shuf -n 1 | sed -r 's/[EM]+/ /g' | sed -e "s/^0//" -e 's/,//g')
    #echo "INFO: pwad map number: $config_pwad_map"
elif [ "$config_pwad_basegame" = "hexen" ]; then
    config_pwad_map=$(cat fileinfo.txt | grep "$config_pwad_name" | grep -E " E[1-5]M" | awk '{print $4}' | shuf -n 1 | sed -r 's/[EM]+/ /g' | sed -e "s/^0//" -e 's/,//g')
    #echo "INFO: pwad map number: $config_pwad_map"
fi

# Remove temporary file
rm fileinfo.txt

echo "$config_pwad_map"